import dayjs from 'dayjs';
import { AccessModel } from '../models/access.model';

export default defineEventHandler(async (event): Promise<any> => {
	const path: string = event.path; // 获取请求路径
	const method: string = event.method; // 获取请求方法
	const ip: string | undefined = event.node.req.socket.remoteAddress; // 获取客户端ip
	const agent: string | undefined = getHeader(event, 'User-Agent'); // 获取客户端信息
	const date = dayjs().format('YYYY年MM月DD日 HH:mm:ss'); // 获取当前时间

	try {
		await AccessModel.create({
			path,
			method,
			ip: ip || '未知',
			agent: agent || '未知',
			date,
		});
	} catch {
		return {
			code: 0,
			message: '访问记录保存失败',
		};
	}
});
